# import jusmargui
from PySide2.QtWidgets import (
    QApplication,
    QWidget,
    QTableWidgetItem,
    QTableWidget,
    QHeaderView,
    QAbstractItemView,
    QVBoxLayout,
    QTabWidget,
    QGroupBox,
    QLabel,
    QLineEdit,
    QHBoxLayout,
    QGridLayout,
    QComboBox,
    QPushButton,
    QListWidget,
    QDialog,
    QButtonGroup,
    QRadioButton,
    QCheckBox,
    QListWidgetItem,
    QMessageBox,
    QGraphicsColorizeEffect,
    QFileDialog,
    QStyledItemDelegate,
    QSizePolicy,
)
from PySide2.QtCore import Qt, Signal
from PySide2.QtGui import QPixmap, QDoubleValidator, QIntValidator, QImage
import sys
import csv
import os
import json
import subprocess
import copy
from gui.controls import envs
from .. import config as Config
from ..utils import Utils
from ..util.parameter_mapping import ConnectionMap, ConnectionReverseMap
from ..dlg_model_params import DlgModeResetCls
from ..params_table import ParamsTable
from ..custom_widget import (
    SelectBox,
    RadioBtnGroup,
    MultRadioBtnGroup,
    LineEditStr,
    LineEditInt,
)


class DlgFixedConnection(DlgModeResetCls):
    fixedConnection_save_signal = Signal(object)

    def __init__(self, parent=None, params={}):
        super().__init__(parent)
        self.setWindowTitle("固定类型连接")
        self.resize(400, 400)

        info = params.get("info") or {}
        self.connectType = info.get("connectType") or ""
        self.connects = info.get("connects") or {}

        layoutWrap = QHBoxLayout()
        layout = QVBoxLayout()
        layoutWrap.addStretch(1)
        layoutWrap.addLayout(layout)
        layoutWrap.addStretch(1)
        self.widgetDict = {}

        gridLayout = QGridLayout()
        self.section1GroupBox = QGroupBox(self.connects[0].get("title") or "Stage1")
        section1Layout = QVBoxLayout()
        self.section1GroupBox.setLayout(section1Layout)
        self.widgetDict["section1"] = SelectBox(
            options=[
                {"title": "点", "value": "点"},
                {"title": "面", "value": "面"},
                {"title": "自由", "value": "自由"},
            ],
            onChanged=lambda *args, **kwargs: self.section1Changed(
                self, *args, **kwargs
            ),
        )

        self.widgetDict["section1Value"] = SelectBox(options=[])
        self.widgetDict["section1"].setFixedWidth(100)
        self.widgetDict["section1Value"].setFixedWidth(100)
        section1Layout.addWidget(self.widgetDict["section1"])
        section1Layout.addWidget(self.widgetDict["section1Value"])

        self.section2GroupBox = QGroupBox(self.connects[1].get("title") or "Ground")
        section2Layout = QVBoxLayout()
        self.section2GroupBox.setLayout(section2Layout)
        self.widgetDict["section2"] = LineEditStr()
        self.widgetDict["section2"].setFixedWidth(100)
        section2Layout.addWidget(self.widgetDict["section2"])

        icon = envs.qicons.qicon_add()
        addImg = QLabel()
        addImg.setAlignment(Qt.AlignCenter)
        pixmap = icon.pixmap(20, 20)
        addImg.setPixmap(pixmap)

        gridLayout.addWidget(self.section1GroupBox, 0, 0)
        gridLayout.addWidget(addImg, 0, 1)
        gridLayout.addWidget(self.section2GroupBox, 0, 2)

        self.connectionIdWidget = self.createContentNumWidget()
        connectionIdLayout = QHBoxLayout()
        layout.addLayout(connectionIdLayout)
        connectionIdLayout.addWidget(self.connectionIdWidget)
        connectionIdLayout.addStretch(1)

        layout.addLayout(gridLayout)

        layout.addStretch(1)

        btnLayout = QHBoxLayout()
        cancelBtn = QPushButton("取消")
        okBtn = QPushButton("确定")

        btnLayout.setAlignment(Qt.AlignCenter)
        btnLayout.addWidget(okBtn)
        btnLayout.addWidget(cancelBtn)
        layout.addLayout(btnLayout)

        okBtn.clicked.connect(self.on_okBtn_clicked)
        cancelBtn.clicked.connect(self.close)

        self.setLayout(layoutWrap)

        if (
            self.connectType == "Stage"
            or self.connectType == "Booster"
            or self.connectType == "Fairing"
        ):
            self.setStageOptions(
                data=self.connects[0].get("data") or {},
                select=self.widgetDict["section1"],
            )
            # self.setStageOptions(data=self.connects[1].get("data") or {}, select=self.widgetDict["section2"])

        self.updateUI(params.get("data") or {})

    def initData(self, params={}):
        info = params.get("info") or {}
        self.connectType = info.get("connectType") or ""
        self.connects = info.get("connects") or {}
        self.section1GroupBox.setTitle(self.connects[0].get("title"))
        self.section2GroupBox.setTitle(self.connects[1].get("title"))
        self.widgetDict["section1"].updateItem(
            [
                {"title": "点", "value": "点"},
                {"title": "面", "value": "面"},
                {"title": "自由", "value": "自由"},
            ]
        )
        # self.widgetDict["section2"].updateItem([
        #         {"title": "点", "value": "点"},
        #         {"title": "面", "value": "面"},
        #         {"title": "自由", "value": "自由"},
        #     ])

        for _, widget in self.widgetDict.items():
            if isinstance(widget, QTableWidget):
                widget.setRowCount(0)
            else:
                widget.setValue("")

        if (
            self.connectType == "Stage"
            or self.connectType == "Booster"
            or self.connectType == "Fairing"
        ):
            self.setStageOptions(
                data=self.connects[0].get("data") or {},
                select=self.widgetDict["section1"],
            )
            # self.setStageOptions(data=self.connects[1].get("data") or {}, select=self.widgetDict["section2"])

        self.updateUI(params.get("data") or {})

    # @classmethod
    # def show(cls, parent=None, params={}):
    #     data1 = Utils.read_json(Config.cachePath + "beamAndMassPoint.json")
    #     data2 = Utils.read_json(Config.cachePath + "skeletalStructure.json")
    #     data3 = Utils.read_json(Config.cachePath + "stringer.json")
    #     params = {
    #         "data": {},
    #         "info": {
    #             "connectType": "Stage",
    #             "connects": [
    #                 {
    #                     "title": "Stage3",
    #                     "data": {
    #                         "sections": [
    #                             {"type": "梁与质量点建模", "data": data1},
    #                             # {"type": "杆系建模", "data": data2},
    #                             # {"type": "蒙皮桁条建模", "data": data3},
    #                         ]
    #                     },
    #                 },
    #                 {
    #                     "title": "Stage4",
    #                     "data": {
    #                         "sections": [
    #                             {"type": "梁与质量点建模", "data": data1},
    #                             {"type": "杆系建模", "data": data2},
    #                         ]
    #                     },
    #                 },
    #             ],
    #         },
    #     }
    #     # params = {
    #     #     "data": {},
    #     #     "info": {
    #     #         "connectType": "Section",
    #     #         "connects": [
    #     #             {
    #     #                 "title": "Section4",
    #     #                 "type": "杆系建模",
    #     #                 "data": data2,
    #     #             },
    #     #             {
    #     #                 "title": "Section3",
    #     #                 "type": "梁与质量点建模",
    #     #                 "data": data1,
    #     #             },

    #     #         ],
    #     #     },
    #     # }
    #     if cls._shown:
    #         cls._instance.activateWindow()
    #         cls._instance.raise_()
    #     else:
    #         cls._shown = True
    #         cls._instance = cls(parent=parent, params=params)  # 创建新实例并传入parent
    #         cls._instance.setParent(parent)  # 设置父窗口
    #         QDialog.show(cls._instance)  # 直接调用QDialog的show方法
    #         return cls._instance

    def getSectionOptionData(self, type, data):
        if not data:
            return []
        options = []
        if type == "梁与质量点建模":
            data = data.get("main") or {}
        elif type == "集中质量建模":
            pass
        elif type == "蒙皮桁条建模":
            data = data.get("ringFrame") or {}
        elif type == "杆系建模":
            data = dict(
                **(data.get("topSurface") or {}), **(data.get("bottomSurface") or {})
            )
        else:
            data = {}
        if data:
            for key, _ in data.items():
                options.append({"title": key, "value": key})
        return options

    def getStageOptionData(self, select, index):
        options = []
        data = {}
        if select == "点":
            # 梁与质量点建模
            ls = (self.connects[index].get("data") or {}).get("sections") or []
            for item in ls:
                if item.get("sectionType") == "梁与质量点建模":
                    itemDict = item.get("data") or {}
                    data.update(itemDict.get("main") or {})
        elif select == "面":
            ls = (self.connects[index].get("data") or {}).get("sections") or []
            for item in ls:
                if item.get("sectionType") == "蒙皮桁条建模":
                    itemDict = item.get("data") or {}
                    data.update(itemDict.get("ringFrame") or {})
                if item.get("sectionType") == "杆系建模":
                    itemDict = item.get("data") or {}
                    data.update(itemDict.get("topSurface") or {})
                    data.update(itemDict.get("bottomSurface") or {})
        if data:
            for key, _ in data.items():
                options.append({"title": key, "value": key})
        return options

    def createContentNumWidget(self):
        connectionIdWidget = QWidget()
        connectionIdWidget.setFixedWidth(240)
        connectionIdLayout = QGridLayout()
        label1 = QLabel("连接编号")
        self.widgetDict["connectionId"] = LineEditInt()
        self.widgetDict["connectionId"].setClearButtonEnabled(False)
        self.widgetDict["connectionId"].setValue(123456)
        connectionIdLayout.addWidget(label1, 0, 0)
        connectionIdLayout.addWidget(self.widgetDict["connectionId"], 0, 1)

        label2 = QLabel("id")
        self.widgetDict["id"] = LineEditInt()
        self.widgetDict["id"].setClearButtonEnabled(False)
        connectionIdLayout.addWidget(label2, 1, 0)
        connectionIdLayout.addWidget(self.widgetDict["id"], 1, 1)

        connectionIdWidget.setLayout(connectionIdLayout)
        return connectionIdWidget

    def createSurfaceWidget(self):
        surfaceGroupBox = QGroupBox("Group")
        surfaceLayout = QVBoxLayout()

        self.widgetDict["allAround"] = MultRadioBtnGroup(
            options=[{"title": "周向全选", "value": "周向全选"}]
        )
        surfaceLayout.addWidget(self.widgetDict["allAround"])
        self.widgetDict["surfaceTable"] = ParamsTable(rows=0, columns=2)
        self.widgetDict["surfaceTable"].setHorizontalHeaderLabels(
            [
                "约束角度",
                "约束范围",
            ]
        )
        self.widgetDict["surfaceTable"].rowSetFloat([0, 1])
        surfaceLayout.addWidget(self.widgetDict["surfaceTable"])
        surfaceGroupBox.setLayout(surfaceLayout)
        return surfaceGroupBox

    def createFreeWidget(self):
        self.widgetDict["freeTable"] = ParamsTable(rows=0, columns=2)
        self.widgetDict["freeTable"].setHorizontalHeaderLabels(
            [
                "主节点",
                "从节点",
            ]
        )
        self.widgetDict["freeTable"].rowSetInt([0])
        return self.widgetDict["freeTable"]

    def on_okBtn_clicked(self):
        dict = {}
        for key, widget in self.widgetDict.items():
            if widget.isVisible():
                if isinstance(widget, QTableWidget):
                    dict[ConnectionMap[key]] = widget.getTableData()
                # elif key == "section1Value" or key == "section2Value":
                #     dict[key] = Utils.toIntOrNone(widget.getValue())
                else:
                    dict[ConnectionMap[key]] = widget.getValue()
        self.close()
        self.fixedConnection_save_signal.emit(dict)

    def section1Changed(self, *args):
        if args[1] == "点":
            if (
                self.connectType == "Stage"
                or self.connectType == "Booster"
                or self.connectType == "Fairing"
            ):
                options = self.getStageOptionData("点", 0)
                self.widgetDict["section1Value"].updateItem(options)
            self.widgetDict["section1Value"].setVisible(True)
        elif args[1] == "面":
            if (
                self.connectType == "Stage"
                or self.connectType == "Booster"
                or self.connectType == "Fairing"
            ):
                options = self.getStageOptionData("面", 0)
                self.widgetDict["section1Value"].updateItem(options)
            self.widgetDict["section1Value"].setVisible(True)
        elif args[1] == "自由":
            self.widgetDict["section1Value"].setVisible(False)

        # self.showTable()

    # def section2Changed(self, *args):
    #     if self.connectType == "Stage" or self.connectType == "Booster" or self.connectType == "Fairing":
    #         if args[1] == "点":
    #                 options = self.getStageOptionData("点", 1)
    #                 self.widgetDict["section2Value"].updateItem(options)
    #         if args[1] == "面":
    #                 options = self.getStageOptionData("面", 1)
    #                 self.widgetDict["section2Value"].updateItem(options)
    #     self.showTable()

    # def showTable(self):
    #     if (
    #         self.widgetDict["section1"].getValue() == "面"
    #     ):
    #         self.surfaceWidget.setVisible(True)
    #         self.freeWidget.setVisible(False)
    #     elif (
    #         self.widgetDict["section1"].getValue() == "自由"
    #     ):
    #         self.surfaceWidget.setVisible(False)
    #         self.freeWidget.setVisible(True)
    #     else:
    #         self.surfaceWidget.setVisible(False)
    #         self.freeWidget.setVisible(False)

    def setStageOptions(self, data, select, previous=""):
        if not data:
            return
        options = []
        sections = data.get("sections")
        if not sections:
            return
        for item in sections:
            if (
                item.get("sectionType") == "梁与质量点建模"
                or item.get("sectionType") == "集中质量建模"
            ):
                if previous == "点" or previous == "面" or previous == "":
                    if {"title": "点", "value": "点"} not in options:
                        options.append({"title": "点", "value": "点"})
            elif (
                item.get("sectionType") == "蒙皮桁条建模"
                or item.get("sectionType") == "杆系建模"
            ):
                if previous == "点" or previous == "面" or previous == "":
                    if {"title": "面", "value": "面"} not in options:
                        options.append({"title": "面", "value": "面"})
            elif item.get("sectionType") == "导入bdf":
                if previous == "自由" or previous == "":
                    if {"title": "自由", "value": "自由"} not in options:
                        options.append({"title": "自由", "value": "自由"})
        select.updateItem(options)

    def updateUI(self, data):
        if data:
            for key, value in data.items():
                widget = ConnectionReverseMap.get(key)
                if widget in self.widgetDict:
                    if isinstance(self.widgetDict[widget], QTableWidget):
                        for rowData in value:
                            self.widgetDict[widget].addRow(rowData=rowData)
                    elif isinstance(self.widgetDict[widget], SelectBox):
                        self.widgetDict[widget].setValue(str(value))
                    else:
                        self.widgetDict[widget].setValue(value)


# if __name__ == "__main__":
#     app = QApplication(sys.argv)
#     window = DlgFixedConnection()
#     window.show()
#     sys.exit(app.exec_())
